package org.linphone.activity;

/*
 ChatListFragment.java
 Copyright (C) 2012  Belledonne Communications, Grenoble, France

 This program is free software; you can redistribute it and/or
 modify it under the terms of the GNU General Public License
 as published by the Free Software Foundation; either version 2
 of the License, or (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program; if not, write to the Free Software
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import org.json.JSONObject;
import org.json.JSONTokener;
import org.linphone.LinphoneService;
import com.leehuubsd.yiyanzb.R;

import org.linphone.Bean.LandedDate;
import org.linphone.core.LinphoneAddress;
import org.linphone.core.LinphoneChatMessage;
import org.linphone.core.LinphoneChatRoom;
import org.linphone.core.LinphoneCoreException;
import org.linphone.core.LinphoneCoreFactory;
import org.linphone.mediastream.Log;
import org.linphone.setup.SetupActivity;

import com.android.volley.AuthFailureError;
import com.android.volley.Request.Method;
import com.android.volley.RequestQueue;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.graphics.Paint;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Parcelable;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.TextUtils;
import android.util.Base64;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView.ScaleType;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

/**
 * @author Sylvain Berfini
 */
public class MoreFragment extends Fragment implements OnClickListener {
	private ViewPager viewPager; // android-support-v4中的滑动组件
	private List<ImageView> imageViews; // 滑动的图片集合
	private String[] titles; // 图片标题
	private TextView tv_title;
	private int[] imageResId; // 图片ID
	private List<View> dots; // 图片标题正文的那些点
	private int currentItem = 0; // 当前图片的索引号
	private ScheduledExecutorService scheduledExecutorService;
	private LinearLayout l1, l2, l3, l4, l5, l6, l7, l8, l9;
	private String OEMID;
	String[] str;
	String urls;

	// 切换当前显示的图片
	private Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			viewPager.setCurrentItem(currentItem);// 切换当前显示的图片
		};
	};

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View v = inflater.inflate(R.layout.activity_square, container, false);
		OEMID = getResources().getString(R.string.oem);
		find(v);
		imageResId = new int[] { R.drawable.banner, R.drawable.banner1 };
		titles = new String[imageResId.length];
		titles[0] = "";
		titles[1] = "";
		imageViews = new ArrayList<ImageView>();
		// 初始化图片资源
		for (int i = 0; i < imageResId.length; i++) {
			ImageView imageView = new ImageView(getActivity());
			imageView.setImageResource(imageResId[i]);
			imageView.setScaleType(ScaleType.FIT_XY);
			imageViews.add(imageView);
		}
		dots = new ArrayList<View>();
		dots.add(v.findViewById(R.id.v_dot0));
		dots.add(v.findViewById(R.id.v_dot1));

		tv_title = (TextView) v.findViewById(R.id.tv_title);
		tv_title.setText(titles[0]);//

		viewPager = (ViewPager) v.findViewById(R.id.vp);
		viewPager.setAdapter(new MyAdapter());// 设置填充ViewPager页面的适配器
		// 设置一个监听器，当ViewPager中的页面改变时调用
		viewPager.setOnPageChangeListener(new MyPageChangeListener());
		scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
		// 当Activity显示出来后，每两秒钟切换一次图片显示
		scheduledExecutorService.scheduleAtFixedRate(new ScrollTask(), 1, 3,
				TimeUnit.SECONDS);
		super.onStart();
		return v;
	}

//	@Override
//	protected void onStart() {
//		scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
//		// 当Activity显示出来后，每两秒钟切换一次图片显示
//		scheduledExecutorService.scheduleAtFixedRate(new ScrollTask(), 1, 3,
//				TimeUnit.SECONDS);
//		super.onStart();
//	}
//
//	@Override
//	protected void onStop() {
//		// 当Activity不可见的时候停止切换
//		scheduledExecutorService.shutdown();
//		super.onStop();
//	}

	private void find(View v) {
		l1 = (LinearLayout) v.findViewById(R.id.square_query);
		l2 = (LinearLayout) v.findViewById(R.id.square_make);
		l3 = (LinearLayout) v.findViewById(R.id.square_website);
		l4 = (LinearLayout) v.findViewById(R.id.square_shop);
		l5 = (LinearLayout) v.findViewById(R.id.square_update);
		l6 = (LinearLayout) v.findViewById(R.id.square_about);
		l7 = (LinearLayout) v.findViewById(R.id.square_set);
		l8 = (LinearLayout) v.findViewById(R.id.square_system);
		l9 = (LinearLayout) v.findViewById(R.id.square_dcpt);
		l1.setOnClickListener(this);
		l2.setOnClickListener(this);
		l3.setOnClickListener(this);
		l4.setOnClickListener(this);
		l5.setOnClickListener(this);
		l6.setOnClickListener(this);
		l7.setOnClickListener(this);
		l8.setOnClickListener(this);
		l9.setOnClickListener(this);

	}
	private static final int WIZARD_INTENT = 1;
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.square_query:
			if (getLandName()) {
				Intent intent0 = new Intent(getActivity(), QueryActivity.class);
				startActivity(intent0);
			} else {
				Toast.makeText(getActivity(), "请先登录在查询", Toast.LENGTH_SHORT)
						.show();
				Intent intent = new Intent(LinphoneService.instance(), SetupActivity.class);
				startActivityForResult(intent, WIZARD_INTENT);
			}
			break;
		case R.id.square_dcpt:
			if (getLandName()) {
				Intent intent3 = new Intent(getActivity(),
						WebsiteActivity.class);
				intent3.putExtra("pathweb",
						getResources().getString(R.string.http)
								+ "/m/pUserCard?userName=" + userName
								+ "&userPwd=" + passWord + "&proxyId=" + OEMID);
				intent3.putExtra("title", "代充平台");
				startActivity(intent3);
			} else {
				Toast.makeText(getActivity(), "请先登录在查询", Toast.LENGTH_SHORT)
						.show();
				Intent intent = new Intent(LinphoneService.instance(), SetupActivity.class);
				startActivityForResult(intent, WIZARD_INTENT);
			}
			break;
		case R.id.square_make:
//			Intent intent2 = new Intent(getActivity(), SquareActivity.class);
//			startActivity(intent2);
			break;
		case R.id.square_website:
			Toast.makeText(getActivity(), "此功能尚未开放", 0).show();
			break;
		case R.id.square_shop:
			// Intent intent3 = new Intent(getActivity(), ShopActivity.class);
			// // startActivity(intent3);
			// Uri uri = Uri.parse("tel:4008296010");
			// Intent it = new Intent(Intent.ACTION_DIAL, uri);
			// startActivity(it);
			break;
		case R.id.square_about:
			Intent intent7 = new Intent(getActivity(), AboutActivity.class);
			startActivity(intent7);
			break;
		case R.id.square_set:
			Intent intent4 = new Intent(getActivity(), SettingActivity.class);
			startActivity(intent4);
			break;
		case R.id.square_system:
			if (getLandName()) {
				try {
					String paths = "http://alipayreturn.leehuu.cn/MobileREST/LiuliangPay/Home?phone="
							+ userName
							+ "&proxyId="
							+ getResources().getString(R.string.oem);
					Uri uri = Uri.parse(paths);
					Intent it = new Intent(Intent.ACTION_VIEW, uri);
					startActivity(it);
				} catch (Exception e) {
					// TODO: handle exception
					Toast.makeText(getActivity(), "未找到可用浏览器", 0).show();
				}
			} else {
				// Intent intenta = new
				// Intent(getActivity(),OldLoginActivity.class);
				// startActivity(intenta);
			}

			break;
		default:
			break;
		}
	}

	private String getVersion() {
		try {
			// 得到包管理器
			PackageManager pm = getActivity().getPackageManager();
			PackageInfo packageInfo = pm.getPackageInfo(getActivity()
					.getPackageName(), 0);
			// 返回版本名
			return packageInfo.versionName;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
			return "";
		}

	}

	private String v;

	protected void UpdateDialog() {

		AlertDialog alertDialog = new AlertDialog.Builder(getActivity())
				.setTitle("更新提示").setMessage("最新版本" + v + "\n" + "是否更新程序")
				.setPositiveButton("确定", new DialogInterface.OnClickListener() {

					public void onClick(DialogInterface dialog, int which) {
						Intent intent = new Intent();
						intent.setData(Uri.parse("http://" + urls));
						intent.setAction(Intent.ACTION_VIEW);
						startActivity(intent);
					}

				}).setNegativeButton("取消",

				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						return;
					}
				}).create(); // 创建对话框
		alertDialog.show(); // 显示对话框
	}

	private String passWord, userName;

	private boolean getLandName() {
		LandedDate landedDate = new LandedDate(getActivity());
		passWord = landedDate.getCardPassword();
		userName = landedDate.getCardNo();
		if (passWord != null || userName != null) {
			return true;
		}
		return false;
	}

	/**
	 * 填充ViewPager页面的适配器
	 * 
	 * @author Administrator
	 * 
	 */
	private class MyAdapter extends PagerAdapter {

		@Override
		public int getCount() {
			return imageResId.length;
		}

		@Override
		public Object instantiateItem(View arg0, int arg1) {
			((ViewPager) arg0).addView(imageViews.get(arg1));
			return imageViews.get(arg1);
		}

		@Override
		public void destroyItem(View arg0, int arg1, Object arg2) {
			((ViewPager) arg0).removeView((View) arg2);
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == arg1;
		}

		@Override
		public void restoreState(Parcelable arg0, ClassLoader arg1) {

		}

		@Override
		public Parcelable saveState() {
			return null;
		}

		@Override
		public void startUpdate(View arg0) {

		}

		@Override
		public void finishUpdate(View arg0) {

		}
	}

	/**
	 * 当ViewPager中页面的状态发生改变时调用
	 * 
	 * @author Administrator
	 * 
	 */
	private class MyPageChangeListener implements OnPageChangeListener {
		private int oldPosition = 0;

		/**
		 * This method will be invoked when a new page becomes selected.
		 * position: Position index of the new selected page.
		 */
		public void onPageSelected(int position) {
			currentItem = position;
			tv_title.setText(titles[position]);
			dots.get(oldPosition).setBackgroundResource(R.drawable.dot_normal);
			dots.get(position).setBackgroundResource(R.drawable.dot_focused);
			oldPosition = position;
		}

		public void onPageScrollStateChanged(int arg0) {

		}

		public void onPageScrolled(int arg0, float arg1, int arg2) {

		}
	}

	/**
	 * 换行切换任务
	 * 
	 * @author Administrator
	 * 
	 */
	private class ScrollTask implements Runnable {

		public void run() {
			synchronized (viewPager) {
				System.out.println("currentItem: " + currentItem);
				currentItem = (currentItem + 1) % imageViews.size();
				handler.obtainMessage().sendToTarget(); // 通过Handler切换图片
			}
		}

	}

}
